package com.nuoniu.sibanyun.service.crm.async;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.nuoniu.sibanyun.entity.SysCompany;
import com.nuoniu.sibanyun.entity.SysEmployee;
import com.nuoniu.sibanyun.entity.SysUser;
import com.nuoniu.sibanyun.entity.crm.CrmCustomer;
import com.nuoniu.sibanyun.entity.crm.CrmHistoryRecord;
import com.nuoniu.sibanyun.entity.crm.CrmStrategy;
import com.nuoniu.sibanyun.mapper.crm.CrmCustomerMapper;
import com.nuoniu.sibanyun.mapper.crm.CrmStrategyMapper;
import com.nuoniu.sibanyun.service.ISysCompanyService;
//import com.nuoniu.sibanyun.service.ISysEmployeeService;
import com.nuoniu.sibanyun.service.crm.ICrmCustomerService;
import com.nuoniu.sibanyun.service.crm.ICrmHistoryRecordService;
import com.nuoniu.sibanyun.service.crm.call.ICrmCallTaskService;
import com.nuoniu.sibanyun.service.impl.SysUserServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@Service
public class CrmAsyncServer {

    @Autowired
    @Lazy
    private ICrmCustomerService crmCustomerService;

//    @Autowired
//    @Lazy
//    private ISysEmployeeService employeeService;

    @Autowired
    @Lazy
    private CrmCustomerMapper crmCustomerMapper;

    @Autowired
    @Lazy
    private ICrmHistoryRecordService crmHistoryRecordService;

    @Autowired
    @Lazy
    private CrmStrategyMapper strategyMapper;

    @Autowired
    @Lazy
    private ISysCompanyService companyService;
    @Autowired
    @Lazy
    private ICrmCallTaskService crmCallTaskService;
    @Autowired
    @Lazy
    private SysUserServiceImpl sysUserService;

    //潜在 策略释放
    @Async
    public void crmStrategy() {
        List<CrmCustomer> ediCrm = new ArrayList<>();
        List<CrmHistoryRecord> crmHistoryRecordList = new ArrayList<>();
        List<SysCompany> companyList = companyService.list();
        for(SysCompany company : companyList) {
            if(company.getId() == 134) {
                Integer cId = company.getId().intValue();
                //首次分配、领用释放策略
                CrmStrategy strategy = strategyMapper.getStrategyByCode("crm_8", cId);
                //潜在客户未联系释放策略
                CrmStrategy strategy1 = strategyMapper.getStrategyByCode("crm_2", cId);
                //潜在未成交释放策略
                CrmStrategy strategy2 = strategyMapper.getStrategyByCode("crm_3", cId);

                if((strategy == null || Integer.valueOf(strategy.getStrategyVal()) < 1) && (strategy1 == null || Integer.valueOf(strategy1.getStrategyVal()) < 1)
                        && (strategy2 == null || Integer.valueOf(strategy2.getStrategyVal()) < 1)) {
                    continue;
                }

                int ranC = 0;
                String[] userIds = {};
                if(strategy1 != null && StringUtils.isNotBlank(strategy1.getAuxiliaryValue())) {
                    userIds = strategy1.getAuxiliaryValue().split(",");
                    if(userIds.length > 0) {
                        int count = userIds.length;
                        Random r = new Random(1);
                        ranC = r.nextInt(count);
                    }
                }

                //获取所有潜在数据
                List<CrmCustomer> customerList = crmCustomerMapper.getListByType(1, cId);
                for(CrmCustomer customer : customerList) {
                    Boolean flag = false;
                    Long collarTime = customer.getCollarTime().toInstant(ZoneOffset.of("+8")).toEpochMilli(); //领用时间
                    Long collarDays = (LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli() - collarTime) / (1000*3600*24); //领用相隔天数
                    if(strategy != null && strategy.getStrategyVal() != null && Long.valueOf(strategy.getStrategyVal()) > 0) {
                        LocalDateTime firstTouchDate = crmCustomerMapper.getFirstTouchDate(customer.getId(), customer.getCollarTime()); //领用后第一次联系时间
                        if(firstTouchDate == null && collarDays >= Long.valueOf(strategy.getStrategyVal())) { //首次领用、分配X天未联系需释放
                            flag = true;
                        }
                    }

                    if(customer.getLastTouchDate() != null && customer.getCollarTime().isBefore(customer.getLastTouchDate())) { //潜在客户X天未联系需释放
                        Long touchTime = customer.getLastTouchDate().toInstant(ZoneOffset.of("+8")).toEpochMilli(); //最后联系时间
                        Long days = (LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli() - touchTime) / (1000*3600*24); //当前时间相差天数
                        if(Long.valueOf(strategy1.getStrategyVal()) > 0 && days >= Long.valueOf(strategy1.getStrategyVal())) {
                            flag = true;
                        }
                    }

                    if(Long.valueOf(strategy2.getStrategyVal()) > 0 && collarDays >= Long.valueOf(strategy2.getStrategyVal())) { //超过X天未成交需释放
                        flag = true;
                    }

                    if(flag) {
                        if(ranC > 0) {
                            SysUser employee = sysUserService.getByUserId(Long.valueOf(userIds[ranC]));
                            if(employee != null) {
                                // 记录领用人
                                customer.setCollarUserId(employee.getId().intValue());
                                customer.setCollarUserName(employee.getRealName());
                                // 记录领用时间
                                customer.setCollarTime(LocalDateTime.now());
                                customer.setOfficeId(employee.getOfficeId().intValue());
                                customer.setOfficeName(employee.getOfficeName());
                                customer.setCollarTime(LocalDateTime.now());
                                ediCrm.add(customer);
                            }
                        } else {
                            // 客户释放并取消共享
                            customer.setCrmType(0);
                            customer.setLastCollarTime(customer.getCollarTime());
                            customer.setLastCollarUserId(customer.getCollarUserId());
                            customer.setLastCollarUserName(customer.getCollarUserName());
                            customer.setReleaseTime(LocalDateTime.now());// 记录释放时间
                            customer.setReleaseUserId(customer.getCollarUserId());
                            customer.setReleaseUserName(customer.getCollarUserName());
                            customer.setCollarUserName("");
                            customer.setShareType(0);
                            customer.setShareMenu("");
                            customer.setShareUserId("");
                            customer.setShareUserName("");
                            UpdateWrapper<CrmCustomer> wrapper = new UpdateWrapper();
                            wrapper.set("collar_time", null);
                            wrapper.set("collar_user_id", null);
                            wrapper.eq("id", customer.getId());
                            crmCustomerService.update(customer, wrapper);

                            // 保存释放记录
                            CrmHistoryRecord historyRecord = new CrmHistoryRecord();
                            historyRecord.setCrmId(customer.getId().intValue());
                            historyRecord.setCrmName(customer.getCrmName());
                            historyRecord.setUserId(customer.getCollarUserId());
                            crmHistoryRecordList.add(historyRecord);
                        }
                    }

                    if(ediCrm.size() > 0) {
                        crmCustomerService.updateBatchById(ediCrm);
                    }
                }
            }
        }
        crmHistoryRecordService.saveBatch(crmHistoryRecordList);
    }

    @Async
    public void checkAndUpdateTaskState(){
        crmCallTaskService.checkAndUpdateTaskState();
    }
}
